package {
    import flash.display.Sprite;
    import flash.xml.XMLDocument;
    import flash.xml.XMLNode;
    import flash.xml.XMLNodeType;
	import flash.text.TextField;

    public class XMLDocumentExample extends Sprite {
		private var msg:TextField = new TextField();

        public function XMLDocumentExample() {
			msg.y=20;
			msg.width = 500;
			msg.height = 500;
			addChild(msg);
            var result:XMLDocument = new XMLDocument();
            result.ignoreWhite = true;
            result.parseXML(getXMLString());

            var books:Array = parseBooks(result.firstChild);
            //trace("books: \n" + books);
			msg.text = "books: \n" + books;
        }

        private function parseBooks(node:XMLNode):Array {
            var books:Array = new Array();

            var kids:Array = node.childNodes;
            for each(var item:XMLNode in kids) {
                parseBook(item, books);
            }

            return books;
        }

        private function parseBook(node:XMLNode, books:Array):void {
            var item:Book = new Book();
            item.setPublisher(node.attributes.publisher);
            item.setName(node.attributes.name);
            books.push(item);
        }

        private function getXMLString():String {
            var list:XML = <books>
                                <book publisher="Addison-Wesley" name="Design Patterns" />
                                <book publisher="Addison-Wesley" name="The Pragmatic Programmer" />
                                <book publisher="Addison-Wesley" name="Test Driven Development" />
                                <book publisher="Addison-Wesley" name="Refactoring to Patterns" />
                                <book publisher="O'Reilly Media" name="The Cathedral & the Bazaar" />
                                <book publisher="O'Reilly Media" name="Unit Test Frameworks" />
                            </books>;
            return list.toXMLString();
        }
    }

}
class Book {
    private var publisher:String;
    private var name:String;

    public function setPublisher(publisher:String):void {
        this.publisher = publisher;
    }

    public function setName(name:String):void {
        this.name = name;
    }

    public function toString():String {
        return "[Book name: " + name + " publisher: " + publisher + "]\n";
    }
}
